import { watch } from "vue";
import { UI, OpAreaConfig } from "@/types";
import { useConfigs, useWorkspace } from "@/features";
import { readStore, writeStore } from "@/utils";

interface WorkspaceStore {
  ui: UI;
  opAreaConfig: OpAreaConfig;
  codeGenConfig: object;
}

const { workspace } = useWorkspace();
const { opAreaConfig, codeGenConfig } = useConfigs();

export function useConfigsStorage() {
  if (workspace.ui === UI.Unknown) {
    throw new Error("workspace尚未初始化");
  }

  const storeKey = `workspace:(${workspace.path})`;

  function refresh() {
    const currentStore = readStore<WorkspaceStore>(storeKey);
    if (!currentStore || currentStore.ui !== workspace.ui) {
      writeStore(storeKey, {
        ui: workspace.ui,
        codeGenConfig,
        opAreaConfig,
      });
      return;
    }

    Object.assign(opAreaConfig, currentStore.opAreaConfig);
    Object.assign(codeGenConfig, currentStore.codeGenConfig);
  }

  function update(key: keyof Omit<WorkspaceStore, "ui">, value: object) {
    const store = readStore<WorkspaceStore>(storeKey);
    if (store) {
      // @ts-expect-error
      store[key] = value;
      writeStore(storeKey, store);
    }
  }

  refresh();

  watch(codeGenConfig, (value) => {
    update("codeGenConfig", value);
  });

  watch(opAreaConfig, (value) => {
    update("opAreaConfig", value);
  });
}
